<!DOCTYPE html><html lang="[&quot;zh-Hans&quot;,&quot;zh-CN&quot;,&quot;default&quot;]"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><meta name="description" content="create-react-app添加mocker和代理功能"><meta name="keywords" content="mock"><meta name="author" content="wenmu"><meta name="copyright" content="wenmu"><title>create-react-app添加mocker和代理功能 | 温木的博客</title><link rel="shortcut icon" href="/melody-favicon.ico"><link rel="stylesheet" href="/css/index.css?version=1.6.1"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@latest/css/font-awesome.min.css?version=1.6.1"><link rel="dns-prefetch" href="https://cdn.staticfile.org"><link rel="dns-prefetch" href="https://cdn.bootcss.com"><link rel="dns-prefetch" href="https://creativecommons.org"><link rel="dns-prefetch" href="http://ta.qq.com"><script>(function() {
   var hm = document.createElement("script");
   hm.src = "https://tajs.qq.com/stats?sId=&lt;script type=&quot;text/javascript&quot; src=&quot;http://tajs.qq.com/stats?sId=66523541&quot; charset=&quot;UTF-8&quot;&gt;&lt;/script&gt;";
   var s = document.getElementsByTagName("script")[0];
   s.parentNode.insertBefore(hm, s);
 })();</script><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  }
} </script><meta name="generator" content="Hexo 4.2.0"></head><body><i class="fa fa-arrow-right" id="toggle-sidebar" aria-hidden="true"></i><div id="sidebar"><div class="toggle-sidebar-info text-center"><span data-toggle="切换文章详情">切换站点概览</span><hr></div><div class="sidebar-toc"><div class="sidebar-toc__title">目录</div><div class="sidebar-toc__progress"><span class="progress-notice">你已经读了</span><span class="progress-num">0</span><span class="progress-percentage">%</span><div class="sidebar-toc__progress-bar"></div></div><div class="sidebar-toc__content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#描述"><span class="toc-number">1.</span> <span class="toc-text">描述</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#添加-mocker-功能"><span class="toc-number">2.</span> <span class="toc-text">添加 mocker 功能</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#设置-proxy"><span class="toc-number">3.</span> <span class="toc-text">设置 proxy</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#proxy-的值"><span class="toc-number">4.</span> <span class="toc-text">proxy 的值</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#和服务端联调"><span class="toc-number">5.</span> <span class="toc-text">和服务端联调</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#设置了-mocker-api-的情况下如何与服务端联调呢？"><span class="toc-number">6.</span> <span class="toc-text">设置了 mocker-api 的情况下如何与服务端联调呢？</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#上面的“启动”和“禁用”为什么要加引号呢？"><span class="toc-number">7.</span> <span class="toc-text">上面的“启动”和“禁用”为什么要加引号呢？</span></a></li></ol></div></div><div class="author-info hide"><div class="author-info__avatar text-center"><img src="https://i.loli.net/2020/02/27/xwaBoOj158MfNyq.jpg"></div><div class="author-info__name text-center">wenmu</div><div class="author-info__description text-center">记录一些在工作中或学习新知识时学到的一些知识点；正所谓好记性不如一个烂笔头，温故而知新！</div><hr><div class="author-info-articles"><a class="author-info-articles__archives article-meta" href="/archives"><span class="pull-left">文章</span><span class="pull-right">115</span></a><a class="author-info-articles__tags article-meta" href="/tags"><span class="pull-left">标签</span><span class="pull-right">52</span></a><a class="author-info-articles__categories article-meta" href="/categories"><span class="pull-left">分类</span><span class="pull-right">30</span></a></div></div></div><div id="content-outer"><div class="no-bg" id="top-container"><div id="page-header"><span class="pull-left"> <a id="site-name" href="/">温木的博客</a></span><i class="fa fa-bars toggle-menu pull-right" aria-hidden="true"></i><span class="pull-right menus"><a class="site-page" href="/">首页</a><a class="site-page" href="/archives">文章</a><a class="site-page" href="/tags">标签</a><a class="site-page" href="/categories">分类</a></span></div><div id="post-info"><div id="post-title">create-react-app添加mocker和代理功能</div><div id="post-meta"><time class="post-meta__date"><i class="fa fa-calendar" aria-hidden="true"></i> 2020-01-09</time><span class="post-meta__separator">|</span><i class="fa fa-inbox post-meta__icon" aria-hidden="true"></i><a class="post-meta__categories" href="/categories/react/">react</a></div></div></div><div class="layout" id="content-inner"><article id="post"><div class="article-container" id="post-content"><h3 id="描述"><a href="#描述" class="headerlink" title="描述"></a>描述</h3><p>本文讲解如何给使用 create-react-app 创建的项目添加 mocker 的功能，和设置添加 proxy 同服务端进行联调。 ###创建项目<br>使用官网方式创建项目。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">npx create-react-app my-app</span><br><span class="line"><span class="built_in">cd</span> my-app</span><br><span class="line">npm install</span><br></pre></td></tr></table></figure>

<a id="more"></a>

<p>弹出配置</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm run eject</span><br></pre></td></tr></table></figure>

<h3 id="添加-mocker-功能"><a href="#添加-mocker-功能" class="headerlink" title="添加 mocker 功能"></a>添加 mocker 功能</h3><p><a href="https://www.npmjs.com/package/mocker-api" target="_blank" rel="noopener">mocker-api 的 npm 地址</a></p>
<p><code>mocker-api</code>是用来启动一个 mocker 服务的插件，使用 mocker-api 可以通过多种方式启动一个 mocker 服务，比如可以像<code>serve</code>插件一样，直接把指定文件启动成一个 mocker 服务,如下：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mocker <span class="string">'./mocker.js'</span></span><br></pre></td></tr></table></figure>

<p>当然也可以在<code>webpack</code>中进行配置，通过<code>webapck</code>进行调用。<br>在<code>webpack</code>的<code>devserver</code>的<code>before</code>函数中进行配置。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install mocker-api --save-dev</span><br></pre></td></tr></table></figure>

<p>打开<code>config/webpackDevServer.config.js</code>文件<br>按照官网上的添加就行，关键代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">'path'</span>);</span><br><span class="line"><span class="keyword">const</span> apiMocker = <span class="built_in">require</span>(<span class="string">'mocker-api'</span>);</span><br><span class="line"></span><br><span class="line">...</span><br><span class="line"></span><br><span class="line">before(app,server)&#123;</span><br><span class="line"></span><br><span class="line">...</span><br><span class="line"></span><br><span class="line">apiMocker(app, path.resolve(<span class="string">"./mocker/index.js"</span>));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>第二个参数一定要定位到一个文件，不能指定一个文件夹。</p>
</blockquote>
<h3 id="设置-proxy"><a href="#设置-proxy" class="headerlink" title="设置 proxy"></a>设置 proxy</h3><p>上面的 code 省去了<code>mocker-api</code>的<code>proxy</code>的配置，经过测试，在<code>mocker-api</code>中设置 proxy 没有作用。下面是官网的 demo</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">// 官网code</span><br><span class="line">+ devServer: &#123;</span><br><span class="line">+   ...</span><br><span class="line">+   before(app)&#123;</span><br><span class="line">+     apiMocker(app, path.resolve(<span class="string">'./mocker/index.js'</span>), &#123;</span><br><span class="line">+       proxy: &#123;</span><br><span class="line">+         <span class="string">'/repos/*'</span>: <span class="string">'https://api.github.com/'</span>,</span><br><span class="line">+         <span class="string">'/:owner/:repo/raw/:ref/*'</span>: <span class="string">'http://127.0.0.1:2018'</span></span><br><span class="line">+       &#125;,</span><br><span class="line">+       changeHost: <span class="literal">true</span>,</span><br><span class="line">+     &#125;)</span><br><span class="line">+   &#125;</span><br><span class="line">+ &#125;,</span><br></pre></td></tr></table></figure>

<p>如果需要开启 proxy，需要设置<code>devServer</code>的<code>proxy</code>属性，但是<code>create-react-app</code>对 proxy 进行了封装，它读取的是 package.json 文件中 proxy 的配置，可查看<code>scripts/start.js</code>中对 proxy 设置的相关代码：</p>
<p>scripts/start.js</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Load proxy config</span></span><br><span class="line"><span class="keyword">const</span> proxySetting = <span class="built_in">require</span>(paths.appPackageJson).proxy;</span><br><span class="line"><span class="keyword">const</span> proxyConfig = prepareProxy(proxySetting, paths.appPublic);</span><br><span class="line"><span class="comment">// Serve webpack assets generated by the compiler over a web server.</span></span><br><span class="line"><span class="keyword">const</span> serverConfig = createDevServerConfig(proxyConfig, urls.lanUrlForConfig);</span><br><span class="line"><span class="keyword">const</span> devServer = <span class="keyword">new</span> WebpackDevServer(compiler, serverConfig);</span><br></pre></td></tr></table></figure>

<p><code>paths.appPackageJson</code>就是<code>package.json</code>文件，然后读取<code>proxy</code>属性。</p>
<h3 id="proxy-的值"><a href="#proxy-的值" class="headerlink" title="proxy 的值"></a>proxy 的值</h3><p>在 package.json 如下设置：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">"proxy"</span>: <span class="string">"http://target_ip:port/"</span></span><br><span class="line">例如：</span><br><span class="line"><span class="string">"proxy"</span>: <span class="string">"http://www.baidu.com/"</span></span><br></pre></td></tr></table></figure>

<h3 id="和服务端联调"><a href="#和服务端联调" class="headerlink" title="和服务端联调"></a>和服务端联调</h3><p>其实 devServer 的 proxy 和 mocker-api 是没关系的，无论 mocker-api 是否存在，只要 devServer 设置了 proxy，就能直接和服务端联调了。</p>
<h3 id="设置了-mocker-api-的情况下如何与服务端联调呢？"><a href="#设置了-mocker-api-的情况下如何与服务端联调呢？" class="headerlink" title="设置了 mocker-api 的情况下如何与服务端联调呢？"></a>设置了 mocker-api 的情况下如何与服务端联调呢？</h3><p>看官方的 demo，mocker 中根据环境变量 NO_PROXY 是“启动”mocker，</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> noProxy = process.env.NO_PROXY === <span class="string">"true"</span>;</span><br><span class="line">...</span><br><span class="line"><span class="built_in">module</span>.exports = noProxy ? &#123;&#125; : delay(proxy, <span class="number">1000</span>);</span><br></pre></td></tr></table></figure>

<p>因此可以通过设置 NO_PROXY“禁用 mocker”，而通过 proxy 和服务端进行联调。如何做呢，很简单，增加一个 npm scripts 命令，看代码：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">"start:no-mock"</span>: <span class="string">"NO_PROXY=true node scripts/start.js"</span>,</span><br></pre></td></tr></table></figure>

<p>是的，仔细的同学应该看到了，就是<strong>复制</strong>了一份<code>start</code>的命令，只是增加了上了环境变量的设置。</p>
<p>如何测试呢？</p>
<blockquote>
<p>我就是使用 mocker 另外启了一个服务，通过 mocker-api 把项目中编写好的 mocker 文件启动了起来。<br><code>mocker ./mocker/index.js</code><br>这个服务的端口和 react 项目的端口肯定不一样，可以进行测试。</p>
</blockquote>
<h3 id="上面的“启动”和“禁用”为什么要加引号呢？"><a href="#上面的“启动”和“禁用”为什么要加引号呢？" class="headerlink" title="上面的“启动”和“禁用”为什么要加引号呢？"></a>上面的“启动”和“禁用”为什么要加引号呢？</h3><blockquote>
<p>因为只要在<code>devServer</code>的<code>before函数</code>中配置了<code>mocker-api</code>，其实<code>mocker</code>服务就启用了，只不过如果<code>mocker</code>文件返回一个空对象，那请求在<code>mocker服务</code>中肯定匹配不到合适的<code>url</code>，然后就走<code>proxy</code>进行请求，而不是<code>mocker服务</code>没启动。</p>
</blockquote>
<p>2019 年 05 月 24 日</p>
</div></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">wenmu</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://blog.wangpengpeng.site/2020/01/09/create-react-app%E6%B7%BB%E5%8A%A0mocker%E5%92%8C%E4%BB%A3%E7%90%86%E5%8A%9F%E8%83%BD/">http://blog.wangpengpeng.site/2020/01/09/create-react-app%E6%B7%BB%E5%8A%A0mocker%E5%92%8C%E4%BB%A3%E7%90%86%E5%8A%9F%E8%83%BD/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank" rel="noopener">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://blog.wangpengpeng.site">温木的博客</a>！</span></div></div><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/mock/">mock</a></div><div class="post-qr-code"><div class="post-qr-code-item"><img class="post-qr-code__img" src="https://i.loli.net/2020/02/27/hOBzIxFDJMCrmtN.jpg"><div class="post-qr-code__desc">微信打赏</div></div></div><nav id="pagination"><div class="prev-post pull-left"><a href="/2020/01/09/byte-%E5%92%8Cstring%E5%8F%8A16%E8%BF%9B%E5%88%B6%E7%9A%84%E8%BD%AC%E6%8D%A2/"><i class="fa fa-chevron-left">  </i><span>byte[]和string及16进制的转换</span></a></div><div class="next-post pull-right"><a href="/2020/01/09/%E5%AE%9E%E7%8E%B0tab%E6%A0%87%E7%AD%BE%E4%B8%8B%E9%80%89%E4%B8%AD%E6%9D%A1%E6%BB%91%E5%8A%A8%E6%95%88%E6%9E%9C-react%E7%BB%84%E4%BB%B6/"><span>实现tab标签下选中条滑动效果-react组件</span><i class="fa fa-chevron-right"></i></a></div></nav><div id="vcomment"></div><script src="https://cdn1.lncld.net/static/js/3.0.4/av-min.js"></script><script src="https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js"></script><script>var notify = 'false' == true ? true : false;
var verify = 'false' == true ? true : false;
var GUEST_INFO = ['nick','mail','link'];
var guest_info = 'nick,mail,link'.split(',').filter(function(item){
  return GUEST_INFO.indexOf(item) > -1
});
guest_info = guest_info.length == 0 ? GUEST_INFO :guest_info;
window.valine = new Valine({
  el:'#vcomment',
  notify:notify,
  verify:verify,
  appId:'U1QqpeQNuBnRsfygHk1GQ30q-gzGzoHsz',
  appKey:'dunDQzEseDzgsKgw4qLQcog1',
  placeholder:'支持markdown！',
  avatar:'wavatar',
  guest_info:guest_info,
  pageSize:'20',
  lang: 'zh-cn'
})</script></div></div><footer><div class="layout" id="footer"><div class="copyright">&copy;2019 - 2020 By wenmu</div><div class="framework-info"><span>驱动 - </span><a href="http://hexo.io" target="_blank" rel="noopener"><span>Hexo</span></a><span class="footer-separator">|</span><span>主题 - </span><a href="https://github.com/Molunerfinn/hexo-theme-melody" target="_blank" rel="noopener"><span>Melody</span></a></div><div class="busuanzi"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span id="busuanzi_container_page_pv">该文访问量<span id="busuanzi_value_page_pv"></span><span></span></span></div></div></footer><i class="fa fa-arrow-up" id="go-up" aria-hidden="true"></i><script src="https://cdn.jsdelivr.net/npm/animejs@latest/anime.min.js"></script><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@latest/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-ui-pack@latest/velocity.ui.min.js"></script><script src="/js/utils.js?version=1.6.1"></script><script src="/js/fancybox.js?version=1.6.1"></script><script src="/js/sidebar.js?version=1.6.1"></script><script src="/js/copy.js?version=1.6.1"></script><script src="/js/fireworks.js?version=1.6.1"></script><script src="/js/transition.js?version=1.6.1"></script><script src="/js/scroll.js?version=1.6.1"></script><script src="/js/head.js?version=1.6.1"></script><script>if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
  $('#nav').addClass('is-mobile')
  $('footer').addClass('is-mobile')
}</script></body></html>